﻿using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using static SimpleWebApi.MyMigration.Models.BusinessLicenseManagement.LegalPerson;

namespace SimpleWebApi.Business.Service.Interface.DTO.BusinessLicenseDTO
{
    public class RelatedPersonCreateDto
    {


        [Required]
        [StringLength(50)]
        public string Name { get; set; } // 姓名


        public string? Ethnicity { get; set; } // 民族

        [Required]
        [StringLength(18, MinimumLength = 18)]
        public string IdNumber { get; set; } // 身份证号

        [StringLength(255)]
        public string? Address { get; set; } // 地址

        [Required]
        [StringLength(20)]
        public string Phone { get; set; } // 联系电话

        [StringLength(50)]
        public string? WeChat { get; set; } // 微信

        
        public EducationLevel Education { get; set; } = EducationLevel.不详;// 学历
    }

    // RelatedPersonDto.cs（用于选择或展示关联人）
    public class RelatedPersonDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string IdNumber { get; set; }
    }


    /// <summary>
    /// 关联人操作DTO（支持新增、更新、删除操作）
    /// </summary>
    public class RelatedPersonOperationDto
    {
        /// <summary>
        /// 关联人ID（更新或删除时必填）
        /// </summary>
        [JsonPropertyName("relatedPersonId")]
        [Range(1, int.MaxValue, ErrorMessage = "关联人ID必须为正整数")]
        public int? RelatedPersonId { get; set; }

        /// <summary>
        /// 关联人更新数据（新增或更新时必填）
        /// </summary>
        [JsonPropertyName("updateData")]
        [RequiredIf(nameof(RelatedPersonId), null, ErrorMessage = "新增关联人时必须提供数据")]
        [ValidateObject]
        public RelatedPersonUpdateDto? UpdateData { get; set; }
    }

    /// <summary>
    /// 关联人更新数据DTO
    /// </summary>
    public class RelatedPersonUpdateDto
    {
        [Required(ErrorMessage = "姓名必填")]
        [StringLength(50, ErrorMessage = "姓名最长50字符")]
        [JsonPropertyName("name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "身份证号必填")]
        [StringLength(18, MinimumLength = 18, ErrorMessage = "身份证号必须18位")]
        [RegularExpression(@"^\d{17}[\dXx]$", ErrorMessage = "身份证号格式错误")]
        [JsonPropertyName("idNumber")]
        public string IdNumber { get; set; }

        [StringLength(20, ErrorMessage = "联系电话最长20字符")]
        [RegularExpression(@"^1[3-9]\d{9}$", ErrorMessage = "手机号格式错误")]
        [JsonPropertyName("phone")]
        public string? Phone { get; set; }
    }

    /// <summary>
    /// 自定义验证：当 relatedPersonId 为空时 UpdateData 必须提供
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class RequiredIfAttribute : ValidationAttribute
    {
        private readonly string _dependentPropertyName;
        private readonly object? _targetValue;

        public RequiredIfAttribute(string dependentPropertyName, object? targetValue = null)
        {
            _dependentPropertyName = dependentPropertyName;
            _targetValue = targetValue;
        }

        protected override ValidationResult? IsValid(object? value, ValidationContext context)
        {
            var instance = context.ObjectInstance;
            var dependentProperty = context.ObjectType.GetProperty(_dependentPropertyName);

            if (dependentProperty == null)
                return new ValidationResult($"无效的依赖字段：{_dependentPropertyName}");

            var dependentValue = dependentProperty.GetValue(instance);

            // 检查条件：当依赖字段的值等于 _targetValue 时，当前字段必填
            if (object.Equals(dependentValue, _targetValue) && value == null)
                return new ValidationResult(ErrorMessage);

            return ValidationResult.Success;
        }
    }

    /// <summary>
    /// 嵌套对象验证
    /// </summary>
    public class ValidateObjectAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext context)
        {
            if (value == null) return ValidationResult.Success;

            var results = new List<ValidationResult>();
            var isValid = Validator.TryValidateObject(
                value,
                new ValidationContext(value),
                results,
                validateAllProperties: true
            );

            return isValid
                ? ValidationResult.Success
                : new ValidationResult(string.Join(", ", results.Select(r => r.ErrorMessage)));
        }
    }
}


